#coding=utf-8
import datetime, pickle
from stconfig import tut_fn
from stockdb import *
import stockdb.misc as misc
import strategy.basic as basic

def breakout_filter(td, n=20, percent=1, level=0):
    pre = td.pre
    if not pre: return False
    
    top = pre.top(n)
    if not top:return False
    
    if td.price.close >= percent * top:
        for i in range(level):
            td = td.pre
            if not td or breakout_filter(td, n , 0):
                return False
        return True
        
    return False

def first_breakout_filter(td, n=20):
    pre_tds = td.pre_n_or_less(n)
    if not pre_tds:return False
    
    rs = []
    for td in pre_tds:
        rs.append( breakout_filter(td, n) )
    
    r = not reduce(lambda x, y: x or y, rs)
    return r
             
def breakout2_filter(td, n=20):
    #条件1:
    r = breakout_filter(td, n)
    if not r:return r
    
    #
    '''
    条件2: 最近10天,至少一有一次20天最高点突破
    '''
    pre_tds = td.pre_n_or_less( n/2 )
    if not pre_tds:return False
    
    rs = []
    for td in pre_tds:
        rs.append( breakout_filter(td, n) )
    
    r = reduce(lambda x, y: x or y, rs)
    return r
    
if __name__ == '__main__':

    today = datetime.date.today().isoformat()
    #date = '2008-08-15'
    date = today
    ratio = 1
    print date, ratio
    
    tds = misc.find_tds_on(date)
    tf = basic.TDFilter(tds)
    tds = tf.filter_by(breakout_filter, 40, ratio).\
             filter_by(basic.tdattr_filter, 'close', 5, 30).\
             all()
             
    cs = []
    for t in tds:
        s = t.fins
        print s.code, s.name
        cs.append(s.code)

    f = open(tut_fn , 'w')
    pickle.dump(cs, f)
